package com.alex.jdbc.transaction.dao.impl;

import com.alex.jdbc.transaction.dao.BookShopDao;
import com.alex.jdbc.transaction.excetion.BookStockException;
import com.alex.jdbc.transaction.excetion.UserAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository("bookShopDao")
public class BookShopDaoImpl implements BookShopDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int findBookPriceByIsbn(String isbn) {
        String sql = "select price from book where isbn=?";
        return jdbcTemplate.queryForObject(sql, Integer.class, isbn);
    }

    @Override
    public int getBookStock(String isbn) {
        String sql = "select stock from book_stock where isbn=?";
        return jdbcTemplate.queryForObject(sql, Integer.class, isbn);
    }

    @Override
    public int getUserAccount(String username) {
        String sql = "select balance from account where username=?";
        return jdbcTemplate.queryForObject(sql, Integer.class, username);
    }

    @Override
    public void updateBookStock(String isbn) {
        // 检查书的库存是否足够
        int bookStock = getBookStock(isbn);
        if (bookStock < 1) {
            throw new BookStockException("库存不足");
        }

        String sql = "update book_stock set stock=stock-1 where isbn=?";
        jdbcTemplate.update(sql, isbn);
    }

    @Override
    public void updateUserAccount(String username, int price) {
        int userAccount = getUserAccount(username);
        if (userAccount < price) {
            throw new UserAccountException("余额不足");
        }

        String sql = "update account set balance=balance-? where username=?";
        jdbcTemplate.update(sql, price, username);
    }
}
